#include <ecal/ecal.h>

#include <atomic>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

class ServiceManager {
 public:
  ServiceManager(size_t count) : server_count_(count) { servers_.reserve(count); }

  void createServers() {
    std::cout << "Creating " << server_count_ << " service servers..." << std::endl;
    for (size_t i = 0; i < server_count_; i++) {
      auto server = std::make_unique<eCAL::CServiceServer>("massive_service_" + std::to_string(i + 1));
      server->AddMethodCallback("echo", "", "", OnMethodCallback);
      servers_.emplace_back(std::move(server));
    }
  }

  // 方法回调（线程安全）
  static int OnMethodCallback(const std::string& method, const std::string&, const std::string&,
                              const std::string& request, std::string& response) {
    request_count_++;
    response = "Processed: " + request;

    if (request_count_ % 100 == 0) {
      std::lock_guard<std::mutex> lock(output_mutex_);
      std::cout << "[" << request_count_ << "] Method: " << method
                << " | Request: " << (request.size() > 20 ? request.substr(0, 20) + "..." : request) << std::endl;
    }

    return 0;
  }

  static std::atomic<long> request_count_;

 private:
  size_t server_count_;
  std::vector<std::unique_ptr<eCAL::CServiceServer>> servers_;
  static std::mutex output_mutex_;
};

std::atomic<long> ServiceManager::request_count_(0);
std::mutex ServiceManager::output_mutex_;

int main(int argc, char** argv) {
  int server_count = 10;
  if (argc > 1) {
    server_count = std::atoi(argv[1]);
    if (server_count < 1) server_count = 1;
    if (server_count > 100) server_count = 100;
  }

  eCAL::Initialize(argc, argv, "Optimized Massive Server");
  eCAL::Process::SetState(proc_sev_healthy, proc_sev_level1, "Service operational");

  ServiceManager manager(server_count);
  manager.createServers();

  while (eCAL::Ok()) {
    std::this_thread::sleep_for(std::chrono::milliseconds(500));
  }

  eCAL::Finalize();

  return 0;
}
